<template>
  <div
      class="bilibili-video-card"
      :class="cardClasses"
      @click="handleVideoClick"
      @mouseenter="handleMouseEnter"
      @mouseleave="handleMouseLeave"
  >
    <!-- 视频封面区域 -->
    <div class="video-cover">
      <!-- 封面图片 -->
      <img
          :src="video.cover"
          :alt="video.title"
          class="cover-image"
          :class="{ loading: imageLoading, error: imageError }"
          @load="handleImageLoad"
          @error="handleImageError"
      />

      <!-- 加载状态 -->
      <div v-if="imageLoading" class="image-loading">
        <el-icon class="loading-icon"><Loading /></el-icon>
      </div>

      <!-- 错误状态 -->
      <div v-if="imageError" class="image-error">
        <el-icon><Picture /></el-icon>
        <span>图片加载失败</span>
      </div>

      <!-- 视频时长 -->
      <div class="video-duration">{{ formatDuration(video.duration) }}</div>

      <!-- 排名徽章 -->
      <div v-if="showRanking && video.ranking" class="ranking-badge" :class="getRankClass(video.ranking)">
        {{ video.ranking }}
      </div>

      <!-- 视频标签 -->
      <div v-if="video.badge" class="video-badge" :class="video.badge.type">
        {{ video.badge.text }}
      </div>

      <!-- 悬停效果层 -->
      <div class="hover-overlay" :class="{ active: isHovering }">
        <div class="play-button">
          <el-icon><VideoPlay /></el-icon>
        </div>
        <div class="hover-stats">
          <span class="stat-item">
            <el-icon><View /></el-icon>
            {{ formatCount(video.playCount) }}
          </span>
          <span class="stat-item">
            <el-icon><ChatDotRound /></el-icon>
            {{ formatCount(video.danmakuCount) }}
          </span>
        </div>
      </div>
    </div>

    <!-- 视频信息区域 -->
    <div class="video-info">
      <!-- 视频标题 -->
      <h3 class="video-title" :title="video.title">
        {{ video.title }}
      </h3>

      <!-- UP主信息 -->
      <div class="up-info" @click.stop="handleUpClick">
        <el-avatar
            :size="24"
            :src="video.upAvatar"
            class="up-avatar"
        >
          <span v-if="!video.upAvatar">{{ video.upName?.charAt(0) }}</span>
        </el-avatar>
        <span class="up-name">{{ video.upName }}</span>
        <el-icon v-if="video.upVerified" class="verify-badge"><Select /></el-icon>
      </div>

      <!-- 视频统计数据 -->
      <div class="video-stats">
        <span class="stat-item">
          <el-icon><View /></el-icon>
          {{ formatCount(video.playCount) }}
        </span>
        <span class="stat-item">
          <el-icon><ChatDotRound /></el-icon>
          {{ formatCount(video.danmakuCount) }}
        </span>
        <span class="publish-time">{{ video.publishTime }}</span>
      </div>

      <!-- 操作按钮 -->
      <div class="video-actions">
        <el-button
            text
            size="small"
            class="action-btn"
            :class="{ 'liked': video.isLiked }"
            @click.stop="handleLike"
        >
          <el-icon><Star /></el-icon>
          {{ formatCount(video.likeCount || 0) }}
        </el-button>

        <el-button
            text
            size="small"
            class="action-btn"
            @click.stop="handleCoin"
        >
          <el-icon><Coin /></el-icon>
          投币
        </el-button>

        <el-button
            text
            size="small"
            class="action-btn"
            :class="{ 'favorited': video.isFavorited }"
            @click.stop="handleFavorite"
        >
          <el-icon><Collection /></el-icon>
          收藏
        </el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import {
  VideoPlay,
  View,
  ChatDotRound,
  Star,
  Coin,
  Collection,
  Select,
  Loading,
  Picture
} from '@element-plus/icons-vue'

const props = defineProps({
  video: {
    type: Object,
    required: true,
    default: () => ({
      id: 1,
      title: '视频标题',
      cover: '',
      upName: 'UP主',
      upAvatar: '',
      upVerified: false,
      playCount: 0,
      danmakuCount: 0,
      duration: '00:00',
      publishTime: '刚刚',
      likeCount: 0,
      isLiked: false,
      isFavorited: false,
      ranking: null,
      badge: null
    })
  },
  showRanking: {
    type: Boolean,
    default: false
  },
  type: {
    type: String,
    default: 'normal', // normal, compact, large
    validator: (value) => ['normal', 'compact', 'large'].includes(value)
  },
  size: {
    type: String,
    default: 'default', // default, small, large
    validator: (value) => ['default', 'small', 'large'].includes(value)
  }
})

const emit = defineEmits(['click', 'like', 'coin', 'favorite', 'up-click'])

const router = useRouter()

// 响应式数据
const imageLoading = ref(true)
const imageError = ref(false)
const isHovering = ref(false)

// 计算属性
const cardClasses = computed(() => {
  return [
    `card-${props.type}`,
    `size-${props.size}`,
    {
      'has-ranking': props.showRanking && props.video.ranking,
      'hovering': isHovering.value
    }
  ]
})

// 处理方法
const handleVideoClick = () => {
  emit('click', props.video)
  // 实际项目中这里会跳转到视频播放页
  router.push(`/video/${props.video.id}`)
}

const handleUpClick = () => {
  emit('up-click', props.video)
  // 跳转到UP主空间
  router.push(`/space/${props.video.upId || props.video.upName}`)
}

const handleLike = async (event) => {
  event.stopPropagation()
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 300))
    emit('like', props.video)
    ElMessage.success(props.video.isLiked ? '取消点赞' : '点赞成功')
  } catch (error) {
    ElMessage.error('操作失败，请重试')
  }
}

const handleCoin = async (event) => {
  event.stopPropagation()
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 300))
    emit('coin', props.video)
    ElMessage.success('投币成功')
  } catch (error) {
    ElMessage.error('投币失败，请重试')
  }
}

const handleFavorite = async (event) => {
  event.stopPropagation()
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 300))
    emit('favorite', props.video)
    ElMessage.success(props.video.isFavorited ? '取消收藏' : '收藏成功')
  } catch (error) {
    ElMessage.error('操作失败，请重试')
  }
}

const handleMouseEnter = () => {
  isHovering.value = true
}

const handleMouseLeave = () => {
  isHovering.value = false
}

const handleImageLoad = () => {
  imageLoading.value = false
  imageError.value = false
}

const handleImageError = (event) => {
  imageLoading.value = false
  imageError.value = true
  console.error('图片加载失败:', event)
  // 设置默认图片
  event.target.src = ''
}

// 工具函数
const formatCount = (count) => {
  if (count >= 100000000) {
    return (count / 100000000).toFixed(1) + '亿'
  } else if (count >= 10000) {
    return (count / 10000).toFixed(1) + '万'
  } else if (count >= 1000) {
    return (count / 1000).toFixed(1) + '千'
  }
  return count.toString()
}

const formatDuration = (duration) => {
  if (!duration) return '00:00'
  // 确保格式为 MM:SS
  const parts = duration.toString().split(':')
  if (parts.length === 1) {
    return `00:${parts[0].padStart(2, '0')}`
  }
  return duration
}

const getRankClass = (rank) => {
  if (rank === 1) return 'rank-1'
  if (rank === 2) return 'rank-2'
  if (rank === 3) return 'rank-3'
  return 'rank-other'
}

onMounted(() => {
  // 预加载图片
  if (props.video.cover) {
    const img = new Image()
    img.onload = handleImageLoad
    img.onerror = handleImageError
    img.src = props.video.cover
  }
})
</script>

<style scoped>
.bilibili-video-card {
  background: white;
  border-radius: 8px;
  overflow: hidden;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  position: relative;
}

.bilibili-video-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15);
}

.bilibili-video-card.hovering {
  transform: translateY(-2px);
}

/* 尺寸变体 */
.size-default {
  width: 100%;
}

.size-small {
  max-width: 200px;
}

.size-large {
  max-width: 320px;
}

/* 视频封面样式 */
.video-cover {
  position: relative;
  width: 100%;
  height: 0;
  padding-bottom: 56.25%; /* 16:9 比例 */
  overflow: hidden;
  border-radius: 8px 8px 0 0;
  background: #f5f5f5;
}

.cover-image {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.3s ease;
}

.bilibili-video-card:hover .cover-image:not(.loading):not(.error) {
  transform: scale(1.05);
}

.cover-image.loading {
  opacity: 0.5;
}

.cover-image.error {
  opacity: 0.3;
}

/* 加载和错误状态 */
.image-loading,
.image-error {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #ccc;
  font-size: 14px;
}

.loading-icon {
  font-size: 24px;
  animation: spin 1s linear infinite;
  margin-bottom: 8px;
}

.image-error .el-icon {
  font-size: 32px;
  margin-bottom: 8px;
}

@keyframes spin {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

/* 视频时长 */
.video-duration {
  position: absolute;
  bottom: 8px;
  right: 8px;
  background: rgba(0, 0, 0, 0.8);
  color: white;
  padding: 2px 6px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
  z-index: 2;
}

/* 排名徽章 */
.ranking-badge {
  position: absolute;
  top: 8px;
  left: 8px;
  width: 24px;
  height: 24px;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: 600;
  color: white;
  font-size: 12px;
  z-index: 2;
}

.rank-1 {
  background: linear-gradient(45deg, #ffd23f, #ffb347);
}

.rank-2 {
  background: linear-gradient(45deg, #c1c1c1, #a8a8a8);
}

.rank-3 {
  background: linear-gradient(45deg, #d4a574, #c19a6b);
}

.rank-other {
  background: rgba(0, 0, 0, 0.7);
}

/* 视频标签 */
.video-badge {
  position: absolute;
  top: 8px;
  right: 8px;
  padding: 2px 6px;
  border-radius: 4px;
  font-size: 10px;
  font-weight: 500;
  color: white;
  z-index: 2;
}

.video-badge.hot {
  background: #ff6b6b;
}

.video-badge.new {
  background: #4ecdc4;
}

.video-badge.recommend {
  background: #45b7d1;
}

/* 悬停遮罩层 */
.hover-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.3s ease;
  z-index: 1;
}

.hover-overlay.active {
  opacity: 1;
}

.play-button {
  width: 48px;
  height: 48px;
  background: rgba(255, 255, 255, 0.9);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #00a1d6;
  font-size: 24px;
  margin-bottom: 12px;
  transition: all 0.3s ease;
}

.play-button:hover {
  background: white;
  transform: scale(1.1);
}

.hover-stats {
  display: flex;
  gap: 16px;
  color: white;
  font-size: 12px;
}

.hover-stats .stat-item {
  display: flex;
  align-items: center;
  gap: 4px;
}

/* 视频信息区域 */
.video-info {
  padding: 12px;
}

.video-title {
  margin: 0 0 8px 0;
  font-size: 14px;
  font-weight: 500;
  color: #18191c;
  line-height: 1.4;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  height: 2.8em;
  transition: color 0.3s ease;
}

.bilibili-video-card:hover .video-title {
  color: #00a1d6;
}

/* UP主信息 */
.up-info {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
  padding: 4px;
  border-radius: 4px;
}

.up-info:hover {
  background: #f5f7fa;
}

.up-avatar {
  flex-shrink: 0;
  transition: transform 0.3s ease;
}

.up-info:hover .up-avatar {
  transform: scale(1.1);
}

.up-name {
  font-size: 12px;
  color: #61666d;
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  transition: color 0.3s ease;
}

.up-info:hover .up-name {
  color: #00a1d6;
}

.verify-badge {
  color: #00a1d6;
  font-size: 12px;
  flex-shrink: 0;
}

/* 视频统计数据 */
.video-stats {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 8px;
  font-size: 11px;
  color: #999;
}

.video-stats .stat-item {
  display: flex;
  align-items: center;
  gap: 2px;
}

.publish-time {
  margin-left: auto;
}

/* 操作按钮 */
.video-actions {
  display: flex;
  justify-content: space-between;
  border-top: 1px solid #f0f0f0;
  padding-top: 8px;
}

.action-btn {
  padding: 4px 8px;
  color: #61666d;
  font-size: 11px;
  transition: all 0.3s ease;
  border: none;
  background: none;
  border-radius: 4px;
}

.action-btn:hover {
  color: #00a1d6;
  background: #f5f7fa;
}

.action-btn.liked {
  color: #ff6b6b;
}

.action-btn.favorited {
  color: #ffd23f;
}

/* 紧凑模式 */
.card-compact .video-info {
  padding: 8px;
}

.card-compact .video-title {
  font-size: 12px;
  height: 2.4em;
  margin-bottom: 6px;
}

.card-compact .up-info {
  margin-bottom: 6px;
}

.card-compact .video-stats {
  font-size: 10px;
}

.card-compact .video-actions {
  padding-top: 6px;
}

.card-compact .action-btn {
  padding: 2px 6px;
  font-size: 10px;
}

/* 大尺寸模式 */
.card-large .video-info {
  padding: 16px;
}

.card-large .video-title {
  font-size: 16px;
  height: 3.2em;
  margin-bottom: 12px;
}

.card-large .up-info {
  margin-bottom: 12px;
}

.card-large .video-stats {
  font-size: 12px;
  margin-bottom: 12px;
}

.card-large .video-actions {
  padding-top: 12px;
}

.card-large .action-btn {
  padding: 6px 12px;
  font-size: 12px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .bilibili-video-card {
    border-radius: 6px;
  }

  .video-info {
    padding: 8px;
  }

  .video-title {
    font-size: 12px;
    height: 2.4em;
  }

  .video-stats {
    font-size: 10px;
  }

  .video-actions {
    display: none;
  }

  .hover-overlay {
    display: none;
  }
}

/* 动画效果 */
@keyframes fadeIn {
  from { opacity: 0; }
  to { opacity: 1; }
}

.bilibili-video-card {
  animation: fadeIn 0.3s ease;
}

/* 无障碍支持 */
.bilibili-video-card:focus {
  outline: 2px solid #00a1d6;
  outline-offset: 2px;
}

/* 高对比度模式支持 */
/* 高对比度模式支持 */
@media (prefers-contrast: more) {
  .bilibili-video-card {
    border: 1px solid CanvasText;
    background-color: Canvas;
    color: CanvasText;
  }

  .video-title {
    font-weight: 600;
    color: CanvasText;
  }

  .video-cover {
    border: 1px solid CanvasText;
  }

  .up-name {
    color: LinkText;
  }

  .video-stats {
    color: GrayText;
  }
}
/* 减少动画模式 */
@media (prefers-reduced-motion: reduce) {
  .bilibili-video-card,
  .cover-image,
  .hover-overlay,
  .play-button,
  .action-btn {
    transition: none;
  }

  .loading-icon {
    animation: none;
  }
}
</style>